/******************************************************************************
 * Copyright 2022 The Airos Authors. All Rights Reserved.
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 * http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 *****************************************************************************/

#include "framework/worker_common.h"

#include "framework/context.h"
#include "framework/log.h"
#include "framework/msg.h"

namespace air {
namespace link {

WorkerCommon::WorkerCommon() {}

WorkerCommon::~WorkerCommon() {}

void WorkerCommon::Idle() {
  if (!context_.expired()) {
    context_.reset();
  }
}

void WorkerCommon::Run() {
  DispatchMsg();
  Work();
}

void WorkerCommon::OnInit() {
  Worker::OnInit();
  LOG(INFO) << "Worker " << GetWorkerName() << " init";
}

void WorkerCommon::OnExit() {
  Worker::OnExit();
  LOG(INFO) << "Worker " << GetWorkerName() << " exit";
}

int WorkerCommon::Work() {
  auto ctx = (context_.expired() ? nullptr : context_.lock());
  if (ctx == nullptr) {
    LOG(ERROR) << "context is nullptr";
    return -1;
  }
  while (RecvMsgListSize() > 0) {
    ctx->Proc(GetRecvMsg());
  }

  return 0;
}

}  // namespace link
}  // namespace air
